﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;

namespace TestAdbCommand
{
    public partial class Form1 : Form
    {
        private List<AdbCommandConfig> commands;
        private Timer pingTimer;
        private Process currentPingProcess;

        public Form1()
        {
            InitializeComponent();
            LoadCommands();
            InitializePingTimer();
        }

        private void InitializePingTimer()
        {
            pingTimer = new Timer();
            pingTimer.Interval = 1000; // 每秒更新一次
            pingTimer.Tick += PingTimer_Tick;
        }

        private void LoadCommands()
        {
            commands = AdbCommandConfig.LoadCommands();
            cmbCommand.DisplayMember = "Name";
            cmbCommand.DataSource = commands;
        }

        private void cmbCommand_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCommand.SelectedItem is AdbCommandConfig selectedCommand)
            {
                txtCommand.Text = selectedCommand.Value;
            }
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (cmbCommand.SelectedItem == null)
            {
                MessageBox.Show("请选择要执行的命令", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var selectedCommand = cmbCommand.SelectedItem as AdbCommandConfig;
            
            // 如果是长ping命令，特殊处理
            if (selectedCommand.Type == 8)
            {
                HandleLongPingCommand(selectedCommand);
            }
            else
            {
                var commandResult = AdbCommandHelper.ExecuteAdbCommand(selectedCommand.Value, selectedCommand.Type);
                txtResult.Text = commandResult.Result;
            }
        }

        private void HandleLongPingCommand(AdbCommandConfig selectedCommand)
        {
            try
            {
                // 如果已经有ping在运行，先停止
                if (currentPingProcess != null && !currentPingProcess.HasExited)
                {
                    StopLongPingProcess();
                    return;
                }

                // 启动长ping
                var commandResult = AdbCommandHelper.ExecuteAdbCommand(selectedCommand.Value, selectedCommand.Type);
                txtResult.Text = commandResult.Result;
                
                if (commandResult.Success)
                {
                    // 启动ping进程并开始定时器
                    StartLongPingProcess(selectedCommand.Value);
                    btnExecute.Text = "停止";
                    pingTimer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行长ping时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void StopLongPingProcess()
        {
            try
            {
                if (currentPingProcess != null && !currentPingProcess.HasExited)
                {
                    currentPingProcess.Kill();
                    currentPingProcess.WaitForExit(3000);
                    currentPingProcess.Dispose();
                    currentPingProcess = null;
                }
                
                pingTimer.Stop();
                btnExecute.Text = "执行";
                txtResult.AppendText($"[{DateTime.Now:HH:mm:ss}] 已停止长ping\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"停止ping进程时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void StartLongPingProcess(string command)
        {
            try
            {
                // 解析IP地址
                string targetIp = "172.26.186.127";
                if (!string.IsNullOrEmpty(command) && command.Contains("ping"))
                {
                    var parts = command.Split(' ');
                    foreach (var part in parts)
                    {
                        if (System.Net.IPAddress.TryParse(part, out _))
                        {
                            targetIp = part;
                            break;
                        }
                    }
                }

                // 启动ping进程
                currentPingProcess = new Process();
                currentPingProcess.StartInfo.FileName = "ping";
                currentPingProcess.StartInfo.Arguments = $"-t {targetIp}";
                currentPingProcess.StartInfo.UseShellExecute = false;
                currentPingProcess.StartInfo.RedirectStandardOutput = true;
                currentPingProcess.StartInfo.RedirectStandardError = true;
                currentPingProcess.StartInfo.CreateNoWindow = true;
                // 修复编码问题，使用GBK编码
                currentPingProcess.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("GBK");
                currentPingProcess.StartInfo.StandardErrorEncoding = Encoding.GetEncoding("GBK");

                currentPingProcess.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        this.Invoke(new Action(() =>
                        {
                            // 确保每行正确显示，添加换行符
                            string line = $"[{DateTime.Now:HH:mm:ss}] {e.Data}";
                            txtResult.AppendText(line + Environment.NewLine);
                            // 自动滚动到底部
                            txtResult.SelectionStart = txtResult.Text.Length;
                            txtResult.ScrollToCaret();
                        }));
                    }
                };

                currentPingProcess.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        this.Invoke(new Action(() =>
                        {
                            string line = $"[{DateTime.Now:HH:mm:ss}] 错误: {e.Data}";
                            txtResult.AppendText(line + Environment.NewLine);
                            txtResult.SelectionStart = txtResult.Text.Length;
                            txtResult.ScrollToCaret();
                        }));
                    }
                };

                currentPingProcess.Start();
                currentPingProcess.BeginOutputReadLine();
                currentPingProcess.BeginErrorReadLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动ping进程失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void PingTimer_Tick(object sender, EventArgs e)
        {
            // 检查ping进程是否还在运行
            if (currentPingProcess != null && currentPingProcess.HasExited)
            {
                pingTimer.Stop();
                btnExecute.Text = "执行";
                txtResult.AppendText($"[{DateTime.Now:HH:mm:ss}] Ping进程已结束" + Environment.NewLine);
                currentPingProcess.Dispose();
                currentPingProcess = null;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtResult.Clear();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 清理资源
            if (currentPingProcess != null && !currentPingProcess.HasExited)
            {
                currentPingProcess.Kill();
                currentPingProcess.Dispose();
            }
            
            pingTimer?.Stop();
            pingTimer?.Dispose();
            
            base.OnFormClosing(e);
        }
    }
}
